<template>
    <div class="chart-wrapper">
        <div ref="chart" class="chart"></div>
    </div>
</template>

<script setup>
    import { watch, ref, onMounted, onUnmounted, markRaw } from 'vue';
    import * as echarts from 'echarts';
    const props = defineProps({
        option:{ type:Object }
    });
    const myChart = ref(null);
    const chart = ref();
    function handleResize(){
        if ( myChart.value ) {
            myChart.value.resize();
        }
    }
    defineExpose({
        instance:myChart
    })
    onMounted(()=>{
        myChart.value = markRaw(echarts.init(chart.value));
        window.addEventListener('resize', handleResize );
    })
    onUnmounted(()=>{
        window.removeEventListener('resize', handleResize);
    })
    watch(()=>props.option, ()=>{
        if ( myChart.value ) {
            let opt = { ...props.option };
            let chartType = opt.series[0].type;
            if ( chartType === 'bar' || chartType === 'line' && !opt.grid ) {
                opt.grid = {
                    top:'15%',
                    left: '4%',
                    right: '4%',
                    bottom: '4%',
                    containLabel: true
                }
            }
            myChart.value.setOption(opt);
        }
    })
</script>

<style lang="scss">
    .chart-wrapper {
        height:100%;
    }
    .chart {
        height:100%;
    }
</style>
